package com.plan.car.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.plan.car.entity.Dept;
import com.plan.car.entity.Post;
import com.plan.car.entity.Role;
import com.plan.car.entity.User;
import com.plan.car.entity.dto.LoginDTO;
import com.plan.car.entity.dto.UserDTO;
import com.plan.car.entity.vo.UserVO;
import com.plan.car.service.DeptService;
import com.plan.car.service.PostService;
import com.plan.car.service.RoleService;
import com.plan.car.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private DeptService deptService;
    @Resource
    private RoleService roleService;
    @Resource
    private PostService postService;
    @PostMapping("login")
    @ApiOperation("登录接口")
    public SaResult doLogin(@RequestBody LoginDTO loginDTO) {
        // 查询用户信息
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername,loginDTO.getUsername());
        List<User> userList = userService.list(userLambdaQueryWrapper);
        if(ObjectUtil.isEmpty(userList)){
           return SaResult.error("账号不存在");
        }else{
            User user = userList.get(0);
            if(!user.getPassword().equals(loginDTO.getPassword())){
                return SaResult.error("密码错误，请重新输入");
            }
            // 登录
            StpUtil.login(user.getUserId());
            // 返回用户信息
            UserVO userVo = new UserVO();
            userVo.setSatoken(StpUtil.getTokenInfo().tokenValue);
            userVo.setUserId(user.getUserId());
            userVo.setUsername(user.getUsername());
            userVo.setName(user.getName());
            Dept dept = deptService.getById(user.getDeptId());
            userVo.setDeptName(dept.getDeptName());
            Post post = postService.getById(user.getPostId());
            userVo.setPostName(post.getPostName());
            Role role = roleService.getById(user.getRoleId());
            userVo.setRoleName(role.getRoleName());
            return SaResult.data(userVo);
        }
    }

    @ApiOperation("注销接口")
    @GetMapping("/logout")
    public SaResult logout(){
        if(StpUtil.isLogin()){
            StpUtil.logout();
            return SaResult.ok("退出登录！");
        } else {
            return SaResult.error("当前未处于登录状态");
        }
    }

    @ApiOperation("修改密码接口")
    @PostMapping("/password")
    public SaResult resetPassword(@RequestBody LoginDTO loginDTO){
        if(StpUtil.isLogin()){
            try{
                long userId = StpUtil.getLoginIdAsLong();
                User loginUser = userService.getById(userId);
                loginUser.setPassword(loginDTO.getPassword());
                loginUser.setUpdateBy(userId);
                loginUser.setUpdateTime(new Date());
                userService.saveOrUpdate(loginUser);
                return SaResult.ok("密码修改成功");
            }catch (Exception e){
                return SaResult.error("密码修改失败");
            }
        } else {
            return SaResult.error("当前未处于登录状态");
        }
    }

    @ApiOperation("查看用户列表接口")
    @GetMapping("/list")
    public SaResult getUserList(){
        if(StpUtil.isLogin()){
            long userId = StpUtil.getLoginIdAsLong();
            User loginUser = userService.getById(userId);
            Role loginRole = roleService.getById(loginUser.getRoleId());
            String roleName = loginRole.getRoleName();
            if(roleName.equals("超级管理员")){
                List<User> userList = userService.list();
                List<UserVO> userVoList = new ArrayList<>();
                for(User user:userList){
                    UserVO userVo = new UserVO();
                    userVo.setUserId(user.getUserId());
                    userVo.setUsername(user.getUsername());
                    userVo.setName(user.getName());
                    Dept dept = deptService.getById(user.getDeptId());
                    userVo.setDeptName(dept.getDeptName());
                    Post post = postService.getById(user.getPostId());
                    userVo.setPostName(post.getPostName());
                    Role role = roleService.getById(user.getRoleId());
                    userVo.setRoleName(role.getRoleName());
                    userVoList.add(userVo);
                }
                return SaResult.data(userVoList);
            } else {
                return SaResult.error("无超级管理员权限");
            }
        } else {
            return SaResult.error("当前未处于登录状态");
        }
    }

    @ApiOperation("新增用户接口")
    @PostMapping("/add")
    public SaResult addUser(@RequestBody UserDTO userDTO){
        if(StpUtil.isLogin()){
            long userId = StpUtil.getLoginIdAsLong();
            User loginUser = userService.getById(userId);
            Role loginRole = roleService.getById(loginUser.getRoleId());
            String roleName = loginRole.getRoleName();
            if(roleName.equals("超级管理员")){
                LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
                userLambdaQueryWrapper.eq(User::getUsername,userDTO.getUsername());
                List<User> userList = userService.list(userLambdaQueryWrapper);
                if(ObjectUtil.isEmpty(userList)){
                    try {
                        User user = new User();
                        user.setUsername(userDTO.getUsername());
                        user.setName(userDTO.getName());
                        user.setPassword(userDTO.getPassword());
                        user.setDeptId(userDTO.getDeptId());
                        user.setRoleId(userDTO.getRoleId());
                        user.setPostId(userDTO.getPostId());
                        user.setCreateBy(userId);
                        user.setCreateTime(new Date());
                        userService.save(user);
                        return SaResult.ok("新增人员成功");
                    }catch (Exception e) {
                        return SaResult.error("新增人员失败");
                    }
                } else {
                    return SaResult.error("账号已存在");
                }
            } else {
                return SaResult.error("无超级管理员权限");
            }
        } else {
            return SaResult.error("当前未处于登录状态");
        }
    }

    @ApiOperation("删除用户接口")
    @PostMapping("/delete")
    public SaResult deleteUser(@RequestBody UserDTO userDTO){
        if(StpUtil.isLogin()){
            long userId = StpUtil.getLoginIdAsLong();
            User loginUser = userService.getById(userId);
            Role loginRole = roleService.getById(loginUser.getRoleId());
            String roleName = loginRole.getRoleName();
            if(roleName.equals("超级管理员")){
                try {
                    userService.removeById(userDTO.getUserId());
                    return SaResult.ok("删除人员成功");
                }catch (Exception e) {
                    return SaResult.error("删除人员失败");
                }
            } else {
                return SaResult.error("无超级管理员权限");
            }
        } else {
            return SaResult.error("当前未处于登录状态");
        }
    }

    @ApiOperation("编辑用户接口")
    @PostMapping("/edit")
    public SaResult editUser(@RequestBody UserDTO userDTO){
        if(StpUtil.isLogin()){
            long userId = StpUtil.getLoginIdAsLong();
            User loginUser = userService.getById(userId);
            Role loginRole = roleService.getById(loginUser.getRoleId());
            String roleName = loginRole.getRoleName();
            if(roleName.equals("超级管理员")){
                try {
                    User user = new User();
                    user.setUserId(userDTO.getUserId());
                    user.setUsername(userDTO.getUsername());
                    user.setName(userDTO.getName());
                    user.setPassword(userDTO.getPassword());
                    user.setDeptId(userDTO.getDeptId());
                    user.setRoleId(userDTO.getRoleId());
                    user.setPostId(userDTO.getPostId());
                    user.setUpdateBy(userId);
                    user.setUpdateTime(new Date());
                    userService.updateById(user);
                    return SaResult.ok("人员更新成功");
                }catch (Exception e) {
                    return SaResult.ok("人员更新失败");
                }
            } else {
                return SaResult.error("无超级管理员权限");
            }
        } else {
            return SaResult.error("当前未处于登录状态");
        }
    }

    @ApiOperation("查询用户接口")
    @PostMapping("/select")
    public SaResult selectUser(@RequestBody UserDTO userDTO){
        if(StpUtil.isLogin()){
            long userId = StpUtil.getLoginIdAsLong();
            User loginUser = userService.getById(userId);
            Role loginRole = roleService.getById(loginUser.getRoleId());
            String roleName = loginRole.getRoleName();
            if(roleName.equals("超级管理员")){
                try {
                    User userInfo = userService.getById(userDTO.getUserId());
                    UserVO userVO = new UserVO();
                    userVO.setUserId(userInfo.getUserId());
                    userVO.setUsername(userInfo.getUsername());
                    userVO.setName(userInfo.getName());
                    Dept dept = deptService.getById(userInfo.getDeptId());
                    userVO.setDeptName(dept.getDeptName());
                    Post post = postService.getById(userInfo.getPostId());
                    userVO.setPostName(post.getPostName());
                    Role role = roleService.getById(userInfo.getRoleId());
                    userVO.setRoleName(role.getRoleName());
                    return SaResult.data(userVO);
                }catch (NullPointerException e) {
                    return SaResult.error("用户不存在");
                }
            } else {
                return SaResult.error("无超级管理员权限");
            }
        } else {
            return SaResult.error("当前未处于登录状态");
        }
    }
}
